package com.cenntro.oss.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.cenntro.common.base.BaseController;
import com.cenntro.common.util.BigDecimalUtil;
import com.cenntro.common.util.GpsTrasformUtil;
import com.cenntro.common.util.result.Result;
import com.cenntro.oss.common.CarUtil;
import com.cenntro.oss.model.dbo.DevCarDO;
import com.cenntro.oss.model.dbo.DevDeviceStaticDO;
import com.cenntro.oss.model.dbo.DevEleDO;
import com.cenntro.oss.model.qo.DeviceTrackQO;
import com.cenntro.oss.model.vo.TrackLogVO;
import com.cenntro.oss.model.vo.TrackVO;
import com.cenntro.oss.service.AliTableStoreService;
import com.cenntro.oss.service.DevCarService;
import com.cenntro.oss.service.DevDeviceStaticService;
import com.cenntro.oss.service.DevEleService;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 
* @ClassName: TrackController
* @Description: 车辆轨迹
* @author 15815
* @date 2019年7月3日
*
 */
@Api(value = "上报记录查询", tags = { "上报记录查询" })
@RestController
@RequestMapping("/track")
public class TrackController extends BaseController {

    @Value("${trackDomain}")
    private String trackUrl;

    @Resource
    private DevDeviceStaticService deviceStaticService;

    @Resource
    private DevCarService devCarService;

    @Resource
    private DevEleService devEleService;

    /**
     * 车辆查询
     * 
     * @return
     */
    @CrossOrigin
    @ApiOperation(value = "上报记录查询", notes = "上报记录查询")
    @RequestMapping(value = "/selectPage")
    public Result selectPage(TrackVO track) {
        return Result.error("查询异常");
    }


    /**
     * 当前行驶轨迹状态
     * 
     * @param
     * @return
     */
    @RequestMapping("/getlogState")
    @ResponseBody
    public Object getlogState(DeviceTrackQO track) {
        Map<String, Object> resultMap = Maps.newHashMap();

        DevDeviceStaticDO staticDO = deviceStaticService.selectById(track.getDevId());
        DevCarDO devCarModel = devCarService.selectById(staticDO.getCarId());
        if (track.getDevId() == null) {
            return Result.error("车辆id不能是空！");
        }
        if (track.getBeginTime() == null || track.getEndTime() == null) {
            return Result.error("时间不能是空， 请设置开始和结束时间！");
        }
        long sevenDay = 1000 * 60 * 60 * 24 * 7 + 1;
        if (track.getEndTime().getTime() - track.getBeginTime().getTime() > sevenDay) {
            return Result.error("轨迹时间超过了7天|Support for querying data for up to 7 days at most！");
        }
        
        List<TrackLogVO> trackLogs = new ArrayList<>();
        Date migrateDate = null;
        try {
            migrateDate = DateUtils.parseDate("2019-08-14 10:00:01", new String[]{"yyyy-MM-dd HH:mm:ss"});  //迁移时间
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (track.getBeginTime().getTime() > migrateDate.getTime()){
            trackLogs = AliTableStoreService.getInstance().getlistTrackLog2(track.getDevId(),staticDO.getImei(), track.getBeginTime(), track.getEndTime(), "newTrackLog");
        }else if(track.getBeginTime().getTime() < migrateDate.getTime()
                && track.getEndTime().getTime() > migrateDate.getTime()
                ) {
            trackLogs = AliTableStoreService.getInstance().getlistTrackLog(staticDO.getImei(), track.getBeginTime(), track.getEndTime());
            List<TrackLogVO> temp = AliTableStoreService.getInstance().getlistTrackLog2(track.getDevId(),staticDO.getImei(), track.getBeginTime(), track.getEndTime(),"newTrackLog");
            trackLogs.addAll(temp);
        }else{
            trackLogs = AliTableStoreService.getInstance().getlistTrackLog2(track.getDevId(), staticDO.getImei(), track.getBeginTime(), track.getEndTime(),"newTrackLog");
        }

        if (trackLogs.size() > 0) {
            resultMap.put("xylist", trackLogs);
            TrackLogVO first = trackLogs.get(0);
            TrackLogVO last = trackLogs.get(trackLogs.size() - 1);
            // 里程是16进制转10进制 在除于10
            Double mileage = BigDecimalUtil.subtract(last.getFaraway(), first.getFaraway()).doubleValue();
            resultMap.put("mileage", mileage);
            /**
             * 使用时长/分钟
             */
            long usetime = (last.getCreatetime().getTime() - first.getCreatetime().getTime()) / 1000 / 60;

            resultMap.put("usetime", usetime);
            resultMap.put("startTime", DateFormatUtils.format(first.getCreatetime(), "MM/dd HH:mm"));
            resultMap.put("endTime", DateFormatUtils.format(last.getCreatetime(), "MM/dd HH:mm"));

            String startAddress = StringUtils.defaultString(first.getCity()) + StringUtils.defaultString(first.getAddress());
            String endAddress = StringUtils.defaultString(last.getCity()) + StringUtils.defaultString(last.getAddress());
            if (StringUtils.isBlank(startAddress)) {
                startAddress = "";
            }
            if (StringUtils.isBlank(endAddress)) {
                endAddress = "";
            }

            Integer startBattery = first.getBattery();
            Integer endBattery = last.getBattery();

            for (TrackLogVO trackLog : trackLogs) {
                if (startBattery == 0 && trackLog.getBattery() > 0) {
                    startBattery = trackLog.getBattery();
                }
                trackLog.setLng(trackLog.getBaidulng());
                trackLog.setLat(trackLog.getBaidulat());
                String time = DateFormatUtils.format(trackLog.getCreatetime(), "yyyy-MM-dd HH:mm:ss");
                trackLog.setTime(time);
                if (devCarModel != null) {
                    trackLog.setHavaKm(CarUtil.getHavaKm(trackLog.getBattery(), devCarModel.getLife()) + "");
                }
                String runAwary = BigDecimalUtil.subtract(trackLog.getFaraway(), first.getFaraway()).setScale(2).toString();
                trackLog.setRunAwary(runAwary);
            }

            Map<String, Object> map = ImmutableMap.of("imei", staticDO.getImei(), "startTime", first.getCreatetime(), "endTime", last.getCreatetime());
            DevEleDO ele = devEleService.selectCharging(map);
            if (ele != null) {
                startBattery += ele.getUpBattery();
            }
            /**
             * 消耗电量
             */
            Double losspower = (startBattery - endBattery) * Double.valueOf(devCarModel.getBattery()) / 100;
            resultMap.put("losspower", losspower);
            resultMap.put("startAddress", startAddress);
            resultMap.put("endAddress", endAddress);

            if (StringUtils.isBlank(startAddress)) {
                String[] str = GpsTrasformUtil.gps2Address(first.getBaidulng(), first.getBaidulat());
                for (String st : str) {
                    if (StringUtils.isNotBlank(st)) {
                        startAddress += st;
                    }
                }
                resultMap.put("startAddress", startAddress);
            }
            if (StringUtils.isBlank(endAddress)) {
                String[] str = GpsTrasformUtil.gps2Address(last.getBaidulng(), last.getBaidulat());
                for (String st : str) {
                    if (StringUtils.isNotBlank(st)) {
                        endAddress += st;
                    }
                }
                resultMap.put("endAddress", endAddress);
            }

            double km100loss = CarUtil.get100Kmloss(mileage, startBattery - endBattery);
            resultMap.put("hundredloss", km100loss);
        }
        return Result.ok(resultMap);
    }
    
    
    
    
}
